package be.android.forap.gui;

import java.util.Map;

import be.android.forap.R;
import be.android.forap.dataprovider.ContactManager;
import be.android.forap.dataprovider.ContactQueries;
import be.android.forap.dataprovider.ForapAdapter;
import be.android.forap.dataprovider.RawContact;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.Toast;

public class ContactsActivity extends BaseActivity {

	public static final String TAG = "ContactsActivity";

	private static final int CHANGE_CONTACT_REQUEST = 0;

	public static final String FILE_OPEN_PUBLICKEY_PATH = "FILE_OPEN_PUBLICKEY_PATH";
	//public static final String SELECTED_CONTACT_ADD_PUBLICKEY = "SELECTED_CONTACT_ADD_PUBLICKEY";

	public static final String HANDLE_EXCHANGE_PK = "HANDLE_EXCHANGE_PK";

	private Button mAddAccountButton;
	private ListView mContactList;
	private CheckBox mShowAllCheckBox;

	private boolean mShowAllContacts;


	/**
	 * Called when the activity is first created. Responsible for initializing the UI.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contactslist);

		String path = getIntent().getStringExtra(FILE_OPEN_PUBLICKEY_PATH);
		if(!TextUtils.isEmpty(path)){
			handlePublicKeyFileOpened(path);
		}

		// Obtain handles to UI objects
		mAddAccountButton = (Button) findViewById(R.id.con_button_addContact);
		mContactList = (ListView) findViewById(R.id.con_listview_contactList);
		mShowAllCheckBox = (CheckBox) findViewById(R.id.con_checkbox_showAllContacts);

		// Initialize class properties
		mShowAllContacts = false;
		mShowAllCheckBox.setChecked(mShowAllContacts);

		mShowAllCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(mShowAllCheckBox.isChecked()){
					mShowAllContacts = true;
					populateContactList();
				}else{
					mShowAllContacts = false;
					populateContactList();
				}

			}
		});

		// Populate the contact list
		populateContactList();
	}

	public void onResume(){
		super.onResume();
		populateContactList();		
	}

	public void onClick(View v){
		switch (v.getId()) {
		case R.id.con_button_addContact:
			Intent i = new Intent(this, ContactAdder.class);
			startActivityForResult(i, CHANGE_CONTACT_REQUEST);		
			break;
		}
	}

	String[] menuItemsForApContact ={"Send","Edit","Delete","Contact Info"};
	String[] menuItemsNonForapContact ={"Add public key"};

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		Log.d(TAG,"---creat context"+ v.getId());
		if (v.getId()==mContactList.getId()) {
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
			String[] menuItems;
			if(((ForapAdapter) mContactList.getAdapter()).isForapRow(info.position)){
				menuItems = menuItemsForApContact;
			}else{
				menuItems = menuItemsNonForapContact;
			}
			menu.setHeaderTitle(" " +  mContactList.getAdapter().getItem(info.position));

			for (int i = 0; i<menuItems.length; i++) {
				menu.add(Menu.NONE, i, i, menuItems[i]);
			}
		}
	}

	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
		int menuItemIndex = item.getItemId();
		String[] menuItems;
		if(((ForapAdapter) mContactList.getAdapter()).isForapRow(info.position)){
			menuItems = menuItemsForApContact;
		}else{
			menuItems = menuItemsNonForapContact;
		}
		String menuItemName = menuItems[menuItemIndex];
		long listItemName = mContactList.getItemIdAtPosition(info.position);

		switch (menuItemIndex) {
		case 0:
			if(menuItemName.equals(menuItemsForApContact[0])){
				sendToSelection(((ForapAdapter) mContactList.getAdapter()).getForapGlobalId(info.position));
			} else {
				addPublicKey(((ForapAdapter) mContactList.getAdapter()).getContactId(info.position),null);
			}

			break;
		case 1:
			editSelection(((ForapAdapter) mContactList.getAdapter()).getForapGlobalId(info.position));
			break;
		case 2:
			deleteSelection(((ForapAdapter) mContactList.getAdapter()).getForapGlobalId(info.position),
					((ForapAdapter) mContactList.getAdapter()).getItem(info.position));
			break; 
		case 3:
			viewContactInfo(((ForapAdapter) mContactList.getAdapter()).getForapGlobalId(info.position));
			break;
		}		
		return true;
	}

	private void sendToSelection(String globalId) {
		Intent sendTo = new Intent(this, EncryptActivity.class);
		sendTo.putExtra(EncryptActivity.SELECTED_GLOBAL_ID, globalId);
		startActivity(sendTo);
	}

	private void addPublicKey(long contactId,String publicKeyPath) {
		Map<String, String> info = ContactQueries.getNamePhoneEmailFromContactId(this, contactId);
		String fullName = info.get("name");
		String fName = info.get("fname");
		String lName =info.get("lname");	
		String phone =info.get("phone");
		String email = info.get("email");

		Intent addPKeyIntent = new Intent(this, ContactAdder.class);
		addPKeyIntent.putExtra(ContactAdder.ADD_PUBLICKEY_CONTACT, true);
		if(!TextUtils.isEmpty(publicKeyPath))
			addPKeyIntent.putExtra(ContactAdder.ADD_PUBLICKEY_PATH, publicKeyPath);
		addPKeyIntent.putExtra(ContactAdder.CONTACT_FNAME, fName);
		addPKeyIntent.putExtra(ContactAdder.CONTACT_LNAME, lName);
		addPKeyIntent.putExtra(ContactAdder.CONTACT_PHONE, phone);
		addPKeyIntent.putExtra(ContactAdder.CONTACT_EMAIL, email);
		startActivityForResult(addPKeyIntent,CHANGE_CONTACT_REQUEST);
	}


	private void editSelection(String globalId) {
		RawContact contact = ContactManager.getRawContactInfo(getApplicationContext(), globalId);
		Intent editIntent = new Intent(this, ContactAdder.class);
		editIntent.putExtra(ContactAdder.EDIT_CONTACT, true);

		Log.d("TAG","edit push"+ contact.getGlobalContactId());
		editIntent.putExtra(ContactAdder.CONTACT_GLOBALID, contact.getGlobalContactId());
		editIntent.putExtra(ContactAdder.CONTACT_FNAME, contact.getFirstName());
		editIntent.putExtra(ContactAdder.CONTACT_LNAME, contact.getLastName());
		editIntent.putExtra(ContactAdder.CONTACT_PHONE, contact.getCellPhone());
		editIntent.putExtra(ContactAdder.CONTACT_EMAIL, contact.getEmail());
		editIntent.putExtra(ContactAdder.CONTACT_PUBKEY, contact.getPublicKeyBlock());
		startActivityForResult(editIntent,CHANGE_CONTACT_REQUEST);
	}

	private void deleteSelection(final String globalId, String name ) {
		AlertDialog.Builder dialog_del = new AlertDialog.Builder(this);
		dialog_del.setTitle("Deleting "+ name)
		.setMessage("Are you sure?")
		.setPositiveButton("Ok", new DialogInterface.OnClickListener() {  

			public void onClick(DialogInterface dialog, int which) {
				if(!TextUtils.isEmpty(globalId)){
					ContactManager.deleteContact(getApplicationContext(), globalId);
					populateContactList();
				} else {
					Toast.makeText(getApplicationContext(), "Error incorrect global id number!", Toast.LENGTH_SHORT).show();
				}
				return;   
			}
		})
		.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				return;   
			}
		})
		.create();
		dialog_del.show();
	}

	private void viewContactInfo(String globalId) {
		Intent i = new Intent(this, ContactInfoActivity.class);
		Log.d(TAG,""+globalId);
		RawContact contact = ContactManager.getRawContactInfo(getApplicationContext(), globalId);
		Log.d(TAG,contact.toString());
		i.putExtra(ContactInfoActivity.INFO_DISPLAYNAME, contact.getFullName());
		i.putExtra(ContactInfoActivity.INFO_PHONE, contact.getCellPhone());
		i.putExtra(ContactInfoActivity.INFO_EMAIL, contact.getEmail());
		i.putExtra(ContactInfoActivity.INFO_PUBLICKEY, contact.getPublicKeyBlock());
		i.putExtra(ContactInfoActivity.INFO_GLOBAL_ID, contact.getGlobalContactId());
		i.putExtra(ContactInfoActivity.INFO_DIRTY, contact.isDirty());
		i.putExtra(ContactInfoActivity.INFO_DELETED, contact.isDeleted());
		startActivity(i);
	}

	/**
	 * Populate the contact list based on account currently selected in the account spinner.
	 */
	private void populateContactList() {
		// Build adapter with contact entries
		ForapAdapter adapter = new ForapAdapter(this,this,mShowAllContacts, true);

		mContactList.setAdapter(adapter);

		mContactList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> l, View v, int position, long id) {
				l.showContextMenuForChild(v);
			}   
		});

		registerForContextMenu(mContactList);
	}

	public void onActivityResult(int reqCode, int resultCode, Intent data) {
		super.onActivityResult(reqCode, resultCode, data);

		switch (reqCode) {
		case (CHANGE_CONTACT_REQUEST) : 
			if(resultCode == Activity.RESULT_OK) {
				populateContactList();
			}
		break;
		}
	}

	private void handlePublicKeyFileOpened(final String path) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		final ForapAdapter adapter = new ForapAdapter(this,this, true, false);

		final String[] contactList = adapter.getDisplayNames();


		builder.setSingleChoiceItems(contactList, 0,	new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {					
			}
		});

		builder.setTitle("Select contact")
		.setPositiveButton("Select", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				ListView list = ((AlertDialog)dialog).getListView();
				addPublicKey(adapter.getContactId(list.getCheckedItemPosition()),path);
			}
		})
		.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.cancel();
			}
		})
		.create();
		builder.show();
	}


}